package com.example.controller;

import com.example.annotation.UserAuth;
import com.example.config.FileUploadConfig;
import com.example.core.Tools;
import com.example.tools.ApiResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;

/**
 * 文件上传控制类
 *
 * @author junelee
 * @date 2020/3/20 20:21
 */
@Api(tags = "文件上传接口")
@RestController
@CrossOrigin
@RequestMapping("/file/")
@UserAuth
public class FileController {

    @Autowired
    private FileUploadConfig fileUploadConfig;

    @ApiOperation(value = "文件上传", notes = "文件上传")
    @PostMapping(value = "upload", headers = "content-type=multipart/form-data")
    public ApiResult<String> uploadImageMany(@RequestParam(value = "file") MultipartFile mf) throws IOException {
        if (mf.isEmpty()) {
            return ApiResult.failed("请传入文件！");
        }
        String TimeDir = Tools.getDate();
        String realPath = fileUploadConfig.getLocation() + TimeDir;
        File file = new File(realPath);
        // 没有目录就创建
        if (!file.exists()) {
            file.mkdirs();
        }
        // 判断文件大小
        String filename = mf.getOriginalFilename();
        // 获取文件后缀
        String ext = filename.substring(filename.lastIndexOf("."), filename.length());
        // 检查文件类型
        if (!Tools.checkExt(fileUploadConfig.getAllowExt(), ext)) {
            return ApiResult.failed("上传文件格式不正确，仅支持" + fileUploadConfig.getAllowExt());
        }
        File targetFile = new File(realPath, filename);
        //开始从源文件拷贝到目标文件
        //传图片一步到位
        mf.transferTo(targetFile);
        String path = fileUploadConfig.getAccessPath()+File.separator+TimeDir+File.separator+targetFile.getName();
       return ApiResult.ok(path);
    }


}
